import {
  Controller, Get, Req, Post, Delete, Body, Query, Param,
  UploadedFile,
  UseInterceptors,
  UnauthorizedException
} from '@nestjs/common';
import { UserService } from './user.service';
import { wrapperResponse } from '../utils/index';
import { CreateUserDto } from './create-user-dto'
import { FileInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import * as path from 'path';
import { JwtService } from '@nestjs/jwt';


@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService, private jwtService: JwtService) {
  }
  @Get('getUserInfo')
  getUserByToken(@Req() request) {
    return wrapperResponse(this.userService.findByUsername(request['user'].username), '获取用户信息成功')
  }

  @Post('postCreateUser')
  create(@Body() user: CreateUserDto) {
    return wrapperResponse(this.userService.create(user), '创建用户成功')
  }

  @Get('list')
  getUserList(@Query() query) {
    return wrapperResponse(this.userService.findUserList(query), '获取用户列表成功')
  }

  @Post('update')
  update(@Body() body: Partial<CreateUserDto>) {
    return this.userService.update(body)
  }

  @Delete('delete/:id')
  remove(@Param('id') id: string) {
    return wrapperResponse(this.userService.batchRemoveUser(id), '删除用户成功')
  }

  @Post('upload')
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: './uploads', // 文件保存路径
        filename: (req, file, callback) => {
          const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
          const ext = path.extname(file.originalname);
          callback(null, `${uniqueSuffix}${ext}`);
        },
      }),
    }),
  )
  async uploadFile(@UploadedFile() file: any, @Req() req: any) {
    const token = req.headers.authorization?.replace('Bearer ', '');

    if (!token) {
      throw new UnauthorizedException('缺少 token');
    }

    try {
      // 验证 JWT
      const decoded = this.jwtService.verify(token);
      console.log('token有效，用户信息:', decoded);
    } catch (error) {
      throw new UnauthorizedException('无效的 token');
    }

    if (!file) {
      throw new Error('未检测到上传文件');
    }

    return wrapperResponse(Promise.resolve({
      url: `/uploads/${file.filename}`,
      filename: file.filename
    }), '上传文件成功')
  }
}
